package cn.springboot.erp.filter;

import cn.hutool.json.JSONUtil;
import cn.springboot.erp.commons.JWTToken;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.utils.JWTUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class WebTokenFilter extends BasicHttpAuthenticationFilter {
    // 设置自定义拦截器


    @Resource
    private JWTUtil jwtUtil;

    // 重写isAccessAllowed方法，实现请求的拦截与放行
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("------------------- WebTokenFilter isAccessAllowed ------------------");

        PrintWriter writer = null;
        try {
            executeLogin(request,response);
            return true;
        } catch (Exception e) {
            e.printStackTrace();

            try {
                response.setContentType("application/json;charset=utf-8");
                writer = response.getWriter();
                String str = JSONUtil.toJsonStr(ResponseResult.Error().msg("token异常，请重新登录"));
                writer.write(str);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }finally {
            if (writer!=null){
                writer.close();
            }
        }

        return false;
    }

    // 重写executeLogin方法，实现form表单的登录认证
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        // 获取请求头携带的token
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("authorization");
        // 判断请求头是否为空
        if (StringUtils.isEmpty(token)){
            throw new RuntimeException("token is empty");
        }

        // 主体认证
        Subject subject = getSubject(request, response);
        JWTToken jwtToken = new JWTToken(token);
        subject.login(jwtToken);
        return true;
    }

    // 重写preHandle方法，处理预检请求
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        // 设置跨域处理
        // 源
        httpServletResponse.setHeader("Access-Control-Allow-Origin",httpServletRequest.getHeader("Origin"));
        // 请求头
        httpServletResponse.setHeader("Access-Control-Allow-Headers",httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 方法
        httpServletResponse.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE");

        // 跨域时会首先发送一个option请求，option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }


        return super.preHandle(request, response);
    }
}
